<template>
  <el-dialog v-el-drag-dialog title="规则配置" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-card style="margin:0 0 5px 5px">
      <el-form ref="dictForm" :model="form" label-width="120px">
        <el-form-item prop="columnId" hidden>
          <el-input v-model="form.columnId" hidden />
        </el-form-item>
        <el-form-item prop="ruleIndex" hidden>
          <el-input v-model="form.ruleIndex" hidden />
        </el-form-item>
        <el-form-item label="数据表名称" prop="tableName">
          <el-input v-model="form.tableName" readonly />
        </el-form-item>
        <el-form-item label="元数据名称" prop="columnName">
          <el-input v-model="form.columnName" readonly />
        </el-form-item>
        <el-button class="m-b-10 fr" type="primary" @click="addRule">添加验证规则</el-button>
        <el-card class="m-b-5 p-b-5 w-100">
          <el-form-item v-for="(rule, index) in rules" :key="index" :label="'验证规则_' + (index + 1)" :inline="true">
            <el-row>
              <el-select v-model="rule.validateName" placeholder="规则名称" @change="changeRule(rule)">
                <el-option
                  v-for="item in optionOfRule"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
              <el-button class="fr" type="danger" round @click="removeRule(rule)">删除</el-button>
            </el-row>
            <el-row>
              <span>规则配置：<i class="help-block fa fa-info-circle">  {{ rule.tag }}</i></span>
              <el-input
                v-model="rule.validateRule"
                type="textarea"
                :rows="2"
              />
            </el-row>
          </el-form-item>
        </el-card>
      </el-form>
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="handleSave">保 存</el-button>
      <el-button type="info" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { loadColumnRule, saveColumnRule } from '@/api/tool/generator'

export default {
  name: 'GenColumnRule',
  props: {
    appendToBody: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      form: {
        columnId: undefined,
        ruleIndex: 0,
        tableName: undefined,
        columnName: undefined
      },
      hasLoaded: false,
      optionOfRule: [],
      ruleTag: {
        notEmpty: 'message:不能为空',
        stringLength: 'min:{0},max:{1},message:长度只能{0}-{1}个字符',
        stringCase: 'case:upper,message:只能包含大写字母',
        emailAddress: 'message:邮箱格式不正确',
        date: 'format: YYYY-MM-DD,message:日期格式不正确',
        digits: 'message:数字格式不正确',
        greaterThan: 'value:{0},message:最小值为{0}',
        lessThan: 'value:{0},message:最大值为{0}',
        identical: 'field:{0},message:与{0}内容不一致',
        choice: 'min:{0},max:{1},message:请选择{0}-{1}项',
        different: 'field:{0},message:与{0}内容相同',
        regexp: 'regexp:^[\\u4e00-\\u9fa5]+$,message:中文格式不正确',
        uri: 'message:网络地址格式不正确',
        remote: 'url:' + this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}` + '/{0},type:{1},delay:{3},message:格式错误'
      },
      rules: []
    }
  },
  methods: {
    init(columnId) {
      this.visible = true
      this.form.columnId = columnId
      this.form.ruleIndex = 0
      this.hasLoaded = false
      this.rules = []
      this.$nextTick(() => {
        this.getRuleData(columnId)
      })
    },
    getRuleData(columnId) {
      this.$dictGroup('gen_column_validate').then(response => {
        this.optionOfRule = response
      }).catch(e => {})
      loadColumnRule(columnId).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        // 添加规则
        const validates = response.param.validates
        this.form.ruleIndex = validates.length
        validates.forEach(validate => {
          this.rules.push({
            validateName: validate.validateName,
            validateRule: validate.rules,
            tag: this.ruleTag[validate.validateName]
          })
        })
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['tool:gen:edit'])
      }).catch(e => {})
    },
    addRule() {
      this.rules.push({
        validateName: '',
        validateRule: '',
        tag: ''
      })
    },
    changeRule(rule) {
      this.rules.map(value => {
        if (rule === value) {
          value.tag = this.ruleTag[rule.validateName]
        }
      })
    },
    removeRule(rule) {
      this.rules.splice(this.rules.indexOf(rule), 1)
    },
    handleSave() {
      if (this.rules.length > 0) {
        this.form.ruleIndex = this.rules.length
        this.rules.forEach((rule, index) => {
          this.form['validateName' + (index + 1)] = rule.validateName
          this.form['validateRule' + (index + 1)] = rule.validateRule
        })
      }
      saveColumnRule(this.form).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.onClose()
      }).catch(() => {})
    },
    onClose() {
      this.$refs.dictForm.resetFields()
      this.rules = []
      this.visible = false
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>
